import { buildMessage, ValidateBy, ValidationArguments, ValidationOptions } from 'class-validator'

/**
 * 判断验证码是否是指定位数（默认 4 位）
 */
export function IsMsgCode(validationOptions?: ValidationOptions & { length?: number }): PropertyDecorator {
    const { length = 4, ...validatorOptions } = validationOptions ?? {}  // 前文默认
    return ValidateBy(
        {
            name: 'IsMsgCode',
            validator: {
                validate: (value: any, args: ValidationArguments): boolean => {
                    return String(value).length === length
                },
                defaultMessage: buildMessage((eachPrefix, args?: ValidationArguments) => {
                    // 用 $property 替换：自动为 'code' 等字段名，无需 object 索引
                    const propertyName = args?.property ?? '$property'  // 安全获取
                    return eachPrefix + ` ${propertyName} 不是一个正确的验证码（需 ${length} 位）`
                }, validatorOptions),
            },
        },
        validatorOptions,
    )
}